package vn.edu.uit.service.fetchers;

import org.json.JSONObject;

import vn.edu.uit.service.UITAPIContant;
import vn.edu.uit.service.UITHttpRequest;
import vn.edu.uit.service.UITService;
import vn.edu.uit.service.UITHttpRequest.RequestMethod;
import android.util.Log;

public class LoginFetcher {
    private static final String LOG_TAG = "LoginFetcher";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_PASSWORD = "password";
    /**
     * The httpRequest to communicate with webservice
     */
    private static UITHttpRequest httpRequest; 
    
    /**
     * The method to check login request 
     * @param email user's email
     * @param password user's password
     * @return If success return 1 and set the token to UITService.TOKEN. If fail return -1.
     */
    public static int checkLogin(String email, String password) {
        UITService.REQUEST_SUCCESS = false;
        httpRequest=new UITHttpRequest(UITAPIContant.API_REST_DOMAIN_URL+UITAPIContant.Api_Functions.CHECK_LOGIN);
        httpRequest.addParam(TAG_EMAIL, email);
        httpRequest.addParam(TAG_PASSWORD, password);
        try {
            JSONObject object = httpRequest.doExecute(RequestMethod.POST);
            Log.d("JSON", object.toString());       
            if(object.getInt(UITService.TAG_ERROR) == 0) {      //request was successful, return 1, set token
                UITService.REQUEST_SUCCESS = true;
                UITService.TOKEN = object.getJSONObject(UITService.TAG_DATA).getString(UITService.TAG_TOKEN);
                return 1;
            } else {                                //request was failed, return -1, set error message
                UITService.REQUEST_SUCCESS = false;
                UITService.MSG = object.getString(UITService.TAG_MSG);
                return -1;
            }   
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e(LOG_TAG, e.getMessage());
        }
        return -1;
    }
}
